#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import paramiko
import os
import subprocess
import hashlib
import time
import shutil
import webbrowser


def joinPath(*paths):
    return '/'.join(list(paths))


class Properties(object):

    def __init__(self, fileName):
        self.fileName = os.path.realpath(fileName)
        self.properties = {}
        try:
            with open(self.fileName, 'Ur') as fopen:
                for line in fopen.readlines():
                    line = line.strip()
                    if not line.startswith('#') and line.find('=') > 0:
                        strs = line.split('=')
                        if len(strs) > 1:
                            self.properties[strs[0].strip()] = strs[1].strip()
        except Exception as e:
            raise e
        finally:
            fopen.close()

    def hasKey(self, key):
        return key in self.properties

    def get(self, key, default_value=None):
        if self.hasKey(key):
            return self.properties[key]
        return default_value


class Linux:

    def __init__(self):
        pass

    # 远程下载文件
    @staticmethod
    def remote_scp(ip, port, remote_path, local_path, file_name, username, password):
        t = paramiko.Transport(ip, port)
        t.connect(username=username, password=password)  # 登录远程服务器
        sftp = paramiko.SFTPClient.from_transport(t)  # sftp传输协议
        src = remote_path + '/' + file_name
        des = local_path + '/' + file_name
        sftp.get(src, des)
        t.close()
        return des

    # 通过用户名密码获取ssh Connection
    @staticmethod
    def getSShConByPassword(ip, port, username, password):
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 通过公共方式进行认证 (不需要在known_hosts 文件中存在)
        ssh.connect(ip, port=port, username=username, password=password)  # 这里要user, pwd
        return ssh

    # 通过密钥来获取ssh Connection
    @staticmethod
    def getSShConByKey(ip, pkey='zhangfan_id_rsa', port=11022, username='zhangfan'):
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 通过公共方式进行认证 (不需要在known_hosts 文件中存在)
        key = paramiko.RSAKey.from_private_key_file(pkey, password='')  # 有解密密码时,
        ssh.connect(ip, port=port, username=username, pkey=key)  # 这里要 pkey passwordkey 密钥文件
        return ssh


class Windows:

    def __init__(self):
        pass

    # 获取文件大小
    @staticmethod
    def fileSize(fileName):
        fileName = os.path.realpath(fileName)
        return os.path.getsize(fileName)

    # 获取文件md5
    @staticmethod
    def MD5(filename):
        filename = os.path.realpath(filename)
        with open(filename, 'rb') as md5file:
            md5 = hashlib.md5(md5file.read()).hexdigest()
        return md5

    # 将文件压缩为.zip
    @staticmethod
    def zip(filename):
        date = time.strftime('%Y%m%d%H%M%S', time.localtime())
        outFileName = 'DB_' + date + '.zip'
        print('outFileName:%s' % outFileName)
        obj = subprocess.Popen(['WinRAR.exe', 'a', '-ep1', outFileName, filename], cwd='.', stderr=subprocess.PIPE,
                               stdout=subprocess.PIPE)
        if obj.stdout.readable():
            out = obj.stdout.read().decode('utf-8')
            print('rar stdout: %s' % out)
            obj.stdout.close()
            return outFileName
        if obj.stderr.readable():
            out = obj.stderr.read().decode('utf-8')
            print('rar stderr: %s' % out)
            obj.stderr.close()
            return out

    # 创建目录(可以在远程局域网操作)
    @staticmethod
    def mkdir(dirName, isDel=False, baseDir='.'):
        path = os.path.realpath(baseDir)
        realdir = joinPath(path, dirName)
        print('realdir:%s' % realdir)
        if not os.path.exists(realdir):
            os.makedirs(realdir)
        else:
            if isDel:
                shutil.rmtree(realdir)  # 递归删除文件夹
                os.makedirs(realdir)
        return realdir

    # 拷贝文件(可以在远程局域网操作)
    @staticmethod
    def cpFile(file, dirs):
        realFilePath = os.path.realpath(file)
        realdir = os.path.realpath(dirs)
        shutil.copy(realFilePath, realdir)

    # 废弃
    @staticmethod
    def ftp_upload(desDirPath, fileName):
        desPath = joinPath(desDirPath, fileName)
        desPath = desPath.replace('/', '\\')
        shutil.copy(fileName, desPath)


class Mail:

    tmpFile = 'tmpFile.html'

    def __init__(self, templateFile):
        self._templateFile = templateFile

    def show(self, content):
        fp = open(self.tmpFile, 'w', encoding='utf8')
        fp.write(content)
        fp.close()
        webbrowser.open(self.tmpFile, new = 0)

        # os.remove(self.tmpFile)

    def readTemplate(self):
        fp = open(self._templateFile, 'Ur', encoding='utf-8')
        content = fp.read()
        fp.close()
        return content